<template>
  <view class="wanl-withdraw">
    <view class="edgeInsetTop"> </view>
    <view class="padding-tb-bj" @tap="$wanlshop.to('/pages/user/bank/bank?choice=1')">
      <view class="bank" v-if="bankData">
        <image :src="`/static/images/bank/${bankData.bankCode}.png`"></image>
        <view class="content">
          <text>{{ bankData.bankName }}</text>
          <view class="wanl-gray">
            <text>尾号 {{ getCode(bankData.cardCode) }} {{ getType(bankData.cardType) }}</text>
          </view>
        </view>
        <view class="action">
          <text class="wlIcon-fanhui2"></text>
        </view>
      </view>
      <view class="bank" v-else>
        <view class="content" style="height: 80rpx; line-height: 80rpx">
          <text>选择提现账户</text>
        </view>
        <view class="action">
          <text class="wlIcon-fanhui2"></text>
        </view>
      </view>
    </view>

    <view class="padding-bj bg-white money">
      <view class="text-lg">
        <text>提现金额</text>
        <text class="text-sm wanl-gray" v-if="servicefee > 0">（费率 {{ servicefee / 10 }}%）</text>
      </view>
      <view class="margin-tb-bj price">
        <view class="symbol">
          <text>￥</text>
        </view>
        <input type="digit" maxlength="5" focus v-model="money" @input="replaceInput" />
        <view class="text-lg wanl-gray-light" @tap="emptyInput" v-if="money">
          <text class="wlIcon-shibai"></text>
        </view>
      </view>
      <view class="solid-top padding-top-bj">
        <block v-if="servicefee > 0">
          <text class="wanl-gray-light">服务费</text>
          <text class="text-price text-orange margin-left-xs">{{ servicemoney }}</text>
          <text class="wanl-gray-light">，</text>
        </block>
        <text class="wanl-gray-light">可用余额</text>
        <text class="wanl-gray-light margin-lr-xs text-price">{{ usermoney }}</text>
        <text class="text-orange" v-if="usermoney > 0" @tap="money = usermoney">全部</text>
      </view>
    </view>
    <view class="padding-bj margin-top">
      <!-- 1.0.5升级 -->
      <button class="mix-btn wanl-bg-redorange" :loading="loading" :disabled="loading" @tap="withdraw">提现</button>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex';
export default {
  data() {
    return {
      bankData: null,
      usermoney: 0,
      money: null,
      servicemoney: 0,
      servicefee: 0,
      loading: false,

      weixin: true,
    };
  },

  computed: {
    ...mapState(['user']),
  },
  /**
   * 监控data中的数据变化
   */
  watch: {
    money: {
      handler(newValue, oldValue) {
        this.servicemoney = this.money > 0 ? ((this.money * this.servicefee) / 1000).toFixed(2) : 0;
      },
      deep: true, //深度监听
      immediate: true, // 立即先去执行里面的handler方法
    },
    'bankData.bankName': {
      handler(newValue, oldValue) {
        console.log('newValue 1========>', newValue);
        setTimeout(() => {
          let id = null;
          // #ifdef H5
          if (this.$jssdk.isWechat()) {
            id = this.user.h5_weixin;
          }
          // #endif
          // #ifdef APP-PLUS
          id = this.user.app_weixin;
          // #endif
          if (this.bankData.bankName == '微信账户' && id == null && this.weixin) {
            this.weixin = false;
            console.log('newValue 2========>', newValue);
            // this.toLogin()
            uni.showModal({
              content: '您还未绑定微信，微信提现无法到账，点击确定请先绑定微信',
              confirmText: '去绑定',
              cancelText: '取消',
              success: response => {
                if (response.confirm) {
                  this.toLogin();
                } else if (response.cancel) {
                }
                this.weixin = true;
              },
            });
          }
        }, 500);
      },
      deep: true, //深度监听
      immediate: true, // 立即先去执行里面的handler方法
    },
  },

  onLoad(option) {
    this.loadData(option.commission || 0);
  },
  methods: {
    async loadData(commission) {
      this.$api.post({
        baseUrl: this.$wanlshop.config('vipBaseUrl'),
        url: '/distribution/user/initialWithdraw',
        success: res => {
          //更新全局金额
          this.setMoney(commission);
          //获取提现账户
          this.bankData = res.bank;
          // 服务费
          this.servicefee = res.servicefee;
        },
      });
    },
    withdraw() {
      // 1.0.5升级 修复针对多次点击
      if (this.loading) return;
      this.loading = true;
      // 1.0.6升级
      let money = parseFloat(this.money),
        usermoney = parseFloat(this.usermoney);
      if (!this.bankData) {
        this.loading = false;
        this.$wanlshop.msg('请选择账号');
        return;
      }
      if (money <= 0) {
        this.loading = false;
        this.$wanlshop.msg('请填写正确金额');
        return;
      }
      if (money > usermoney) {
        this.loading = false;
        this.$wanlshop.msg('提现金额不能超过 ' + usermoney + ' 元');
        return;
      }

      let method = null;

      // #ifdef H5
      if (this.$jssdk.isWechat()) {
        method = 'mp';
      }
      // #endif
      // #ifdef APP-PLUS
      method = 'app';
      // #endif

      this.$api.post({
        url: '/distribution/user/withdraw',
        baseUrl: this.$wanlshop.config('vipBaseUrl'),
        data: {
          money: money,
          account_id: this.bankData.id,
          method: method, // app=app,mp=公众号提现
        },
        success: res => {
          console.log('提现初始化信息 ========>', res);
          this.setMoney(res.money);
          // 1.0.5升级
          this.loading = false;
          // 跳转成功
          this.$wanlshop.to('/pages/page/success?type=teamWithdraw');
        },
        complete: () => {
          this.loading = false;
        },
      });

      // this.$api.post({
      // 	url: '/wanlshop/pay/withdraw',
      // 	data: {
      // 		money: money,
      // 		account_id: this.bankData.id
      // 	},
      // 	success: res => {
      // 		this.setMoney(res);
      // 		// 1.0.5升级
      // 		this.loading = false;
      // 		// 跳转成功
      // 		this.$wanlshop.to('/pages/page/success?type=withdraw');
      // 	}
      // });
    },
    setMoney(money) {
      this.usermoney = money;
      // this.$store.commit('user/setUserInfo', {money: money});
    },
    replaceInput(e) {
      this.money = e.target.value;
      // this.servicemoney = e.target.value > 0 ? (e.target.value*this.servicefee/1000).toFixed(2) : 0;
    },
    emptyInput() {
      this.money = null;
    },
    getCode(str) {
      str = str.replace(/\s+/g, '');
      return str.substring(str.length - 4);
    },
    getType(key) {
      return ['储蓄卡', '信用卡'][key];
    },
    toLogin() {
      // #ifdef APP-PLUS
      uni.login({
        provider: 'weixin',
        success: loginRes => {
          this.$api.post({
            url: '/wanlshop/user/third',
            data: {
              platform: 'app_weixin',
              loginData: loginRes,
              client_id: uni.getStorageSync('wanlshop:chat_client_id')
                ? uni.getStorageSync('wanlshop:chat_client_id')
                : null,
            },
            success: res => {
              // uni.hideLoading();
              // if (res.binding == 0) {
              // this.$wanlshop.to(`/pages/user/auth/perfect?third_id=${res.third_id}&platform=app_weixin&url=${this.pageroute}`);
              // }else{
              this.$store.dispatch('user/login', res);
              // this.$store.dispatch('cart/login');
              // this.$store.dispatch('chat/get');
              // uni.reLaunch({url: decodeURIComponent(this.pageroute)});
              // }

              this.$api.post({
                url: '/wanlshop/user/refresh',
                success: res => {
                  this.$store.commit('statistics/edit', res.statistics);
                  this.$store.commit('user/setUserInfo', res.userinfo);
                },
              });
            },
          });
          // 隐藏键盘
          uni.hideKeyboard();
        },
        fail: err => {
          this.$wanlshop.msg(err.msg);
        },
      });
      // #endif
    },
  },
};
</script>

<style>
.wanl-withdraw .money .symbol {
  font-size: 60rpx;
  margin-right: 10rpx;
}

.wanl-withdraw .money .price {
  display: flex;
  align-items: center;
}
.wanl-withdraw .money .price input {
  /* #ifdef MP */
  height: 100rpx;
  min-height: 100rpx;
  /* #endif */
  width: 100%;
  font-size: 100rpx;
}

.wanl-withdraw .bank {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
  padding: 20rpx 25rpx;
}
.wanl-withdraw .bank image {
  width: 100rpx;
  height: 100rpx;
  margin-right: 25rpx;
}
.wanl-withdraw .bank .content {
  flex: 1;
}
.wanl-withdraw .bank .action {
}
</style>
